__author__="Diego Rodriguez"
__date__ ="$08/16/2010 09:53:59 PM$"
from os import path, walk
from ftplib import FTP
import smtplib
import mimetypes
from email.MIMEText import MIMEText
import socket
import sys
import time
import datetime
import shutil
import os
#########################################################################                                           #
#                                                                       #
# Copyright (C) 2010 LeXeL                                              #
#                                                                       #
# This program is free software: you can redistribute it and/or modify  #
# it under the terms of the GNU General Public License as published by  #
# the Free Software Foundation, either version 3 of the License, or     #
# any later version.                                                    #
#                                                                       #
# This program is distributed in the hope that it will be useful,       #
# but WITHOUT ANY WARRANTY; without even the implied warranty of        #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
# GNU General Public License for more details.                          #
#                                                                       #
# You should have received a copy of the GNU General Public License     #
# along with this program.  If not, see <http://www.gnu.org/licenses/>. #
#########################################################################
class Log_finder(object):
    def __init__(self):
        self.ftp_server=""#FTP server
        self.ftp_user=""#FTP user
        self.ftp_pass=""#FTP pass
        self.smtp_server="smtp.gmail.com"#SMTP server (irecomend gmail ;))
        self.smtp_user=""#SMTP user
        self.smtp_pass=""# SMTP password
        self.directorio2move="/Mysecretlogfolder"# directory where logs files will be moved
        self.TUEMAIL = ""# your email
        self.archivosLogs=[]
        self.archivos=[]
    def titulo(self):
        tit = """ \n
\t  ________  __                  __  __                           
\t /        |/  |                /  |/  |                          
\t $$$$$$$$/ $$/  _______    ____$$ |$$ |        ______    ______  
\t $$ |__    /  |/       \  /    $$ |$$ |       /      \  /      \ 
\t $$    |   $$ |$$$$$$$  |/$$$$$$$ |$$ |      /$$$$$$  |/$$$$$$  |
\t $$$$$/    $$ |$$ |  $$ |$$ |  $$ |$$ |      $$ |  $$ |$$ |  $$ |
\t $$ |      $$ |$$ |  $$ |$$ \__$$ |$$ |_____ $$ \__$$ |$$ \__$$ |
\t $$ |      $$ |$$ |  $$ |$$    $$ |$$       |$$    $$/ $$    $$ |
\t $$/       $$/ $$/   $$/  $$$$$$$/ $$$$$$$$/  $$$$$$/   $$$$$$$ |
\t                                                       /  \__$$ |
\t                                                       $$    $$/ 
\t                                                        $$$$$$/ 

\tHerramienta Creada por: LeXeL : lexelEZ[at]gmail[dot]com\n\n"""
        print "*"*80
        print tit
        print "*"*80
    def sender(self):
        log_ip = "log"
        ftp = FTP(self.ftp_server)
        ftp.login(user=self.ftp_user,passwd=self.ftp_pass)
        arc = str(self.archivos)
        arc = arc.replace("['", "")
        arc = arc.replace("']", "")
        for dic in self.archivosLogs:
        
            print ">>>>>>> %s" %(dic)
            f = open (dic ,"rb")
            ftp.cwd("/log")
            ftp.storbinary('STOR '+arc,f)
            self.mover()
            self.correo()
            self.archivosLogs.remove(dic)
            self.archivos.remove(arc)

            
            
    def mover(self):
        if "Mysecretlogfolder" in os.listdir("/"):
            for dirc in self.archivosLogs:
                try:
                    shutil.move(dirc,self.directorio2move)
                
                except:
                    print "There was an Error\nPlease check this:"
                    print "\t[-]The directory %s" %(self.directorio2move)
                    print "\t[-]check if the file already exist's"
                    sys.exit(1)
        elif "Mysecretlogfolder" not in os.listdir("/"):
            os.system("mkdir %s" %(self.directorio2move))
            for dirc in self.archivosLogs:
                try:
                    shutil.move(dirc,self.directorio2move)
                except:
                    print "There was an Error\nPlease check this:"
                    print "\t[-]The directory %s" %(self.directorio2move)
                    print "\t[-]check if the file already exist's"
                    sys.exit(1)
        else:
            print "[-] Could't create the directory!"
            
            
    def info(self):
        now = datetime.datetime.now()
        now =str(now)
        d = ""
        for dic in self.archivosLogs:
            d += "We have found a Log file in: %s\n" %(dic)
            a =  "The log file have been moved to %s" %(self.directorio2move)
        return """Your local Time is :%s\n %s \n %s  """  %(now,d,a)
        
    def correo(self):
        if self.SMTPTF == True:
            smtp = smtplib.SMTP('smtp.gmail.com',25)
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(self.smtp_user,self.smtp_pass)
            mensaje = MIMEText(self.info())
            mensaje['From']=self.smtp_user
            mensaje['To']=self.TUEMAIL
            mensaje['Subject']="Se ha Encontrado un Log File en tu systema"
            smtp.sendmail(self.smtp_user,self.TUEMAIL,mensaje.as_string())

                
    def conecter(self):
        self.titulo()
        fserver = self.ftp_server
        fuser=self.ftp_user
        fpass=self.ftp_pass
        sserver=self.smtp_server
        suser=self.smtp_user
        spass=self.smtp_pass
        try:
            ftp = FTP(fserver)
            ftp.login(user=fuser,passwd=fpass)
        except BaseException, e:

            print '\n [-] Error: %s ' %(e)
        else:
            print "[*]Sucessfuly conencted to: %s" %(fserver)
        if "log" in ftp.nlst():
            print "[+] Found a Log file on the FTP server"
        if "log" not in ftp.nlst():
            print "[+] Creating a Log directory on the FTP server"
            ftp.mkd("/log")
            

        try:
            smtp = smtplib.SMTP(sserver,25)
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(suser,spass)
        except BaseException, e:
            print '\n [-] Error: %s ' %(e)
            self.SMTPTF = False
        else:
            print "[*]Sucessfuly conencted to: %s" %(sserver)
            self.SMTPTF = True



    def buscador(self):
        
        try:
            path_to_search = raw_input("Please enter the path to scan: ")
            timetowait = input("Please enter the time to sleep in seconds: ")
            print "The Program Just start Please wait"
            print "Found:"
        except KeyboardInterrupt, IOError:
            print "[-] An Error occured \n Quiting!"
            sys.exit(1)
        while True:
            now = datetime.datetime.now()
            for root, dirs, files in walk(path_to_search):
                for archivo in files:
                    (shortname, extension) = path.splitext(archivo)   
                                   
                    if extension=='.log':
                        formato = shortname+" | "+str(now)
                        archivo2 = formato+extension
                        self.archivosLogs.append(path.join(root, archivo))
                        self.archivos.append(archivo2)
                        self.sender()
            time.sleep(timetowait)


                        
if __name__ == '__main__':
    Log = Log_finder()
    Log.conecter()
    Log.buscador()
